package com.yincai.carefreewater.ui;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.yincai.carefreewater.R;
import com.yincai.carefreewater.entity.Weather;
import com.yincai.carefreewater.tool.JumpTool;
import com.yincai.carefreewater.tool.ToastTool;
import com.yincai.carefreewater.tool.WindowTool;
import com.google.gson.Gson;
import com.pili.pldroid.player.AVOptions;
import com.pili.pldroid.player.PLMediaPlayer;
import com.pili.pldroid.player.widget.PLVideoView;
import com.yincai.carefreewater.callback.MyHttpCallback;
import com.yincai.carefreewater.callback.StringCallback;
import com.yincai.carefreewater.constant.URLConstant;
import com.yincai.carefreewater.db.AvdDao;
import com.yincai.carefreewater.db.AvdVersion;
import com.yincai.carefreewater.db.Drink;
import com.yincai.carefreewater.db.DrinkDao;
import com.yincai.carefreewater.db.PlayDao;
import com.yincai.carefreewater.db.PlayRecord;
import com.yincai.carefreewater.db.RequestDao;
import com.yincai.carefreewater.db.RequestRecord;
import com.yincai.carefreewater.db.SaveDao;
import com.yincai.carefreewater.db.SaveInfo;
import com.yincai.carefreewater.db.UpPlay;
import com.yincai.carefreewater.entity.Advertising;
import com.yincai.carefreewater.entity.DringkWater;
import com.yincai.carefreewater.entity.WarnCode;
import com.yincai.carefreewater.tool.DateTimeUtil;
import com.yincai.carefreewater.tool.ShareTool;
import com.yincai.carefreewater.tool.VersionTools;
import com.yincai.carefreewater.usb.UsbTool;
import com.yincai.carefreewater.video.Config;
import com.yincai.carefreewater.video.PermissionChecker;
import com.yincai.carefreewater.video.Utils;
import com.yincai.carefreewater.video.VideoPlayerBaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 主页
 */
public class MainActivity extends VideoPlayerBaseActivity {
    @BindView(R.id.main_wifi)
    ImageView mainWifi;
    @BindView(R.id.main_set)
    ImageView mainSet;
    @BindView(R.id.pl_video)
    PLVideoView mVideoView;
    @BindView(R.id.main_msg)
    TextView mainMsg;
    @BindView(R.id.main_head)
    CircleImageView mainHead;
   @BindView(R.id.main_power)
   ImageView mainPower;
    @BindView(R.id.main_real)
    RelativeLayout mainReal;
    private boolean mIsLiveStreaming;
    private boolean mIsActivityPaused = true;
    private Toast mToast = null;
    private static final int MESSAGE_ID_RECONNECTING = 0x01;
    private final int WRITE_COARSE_LOCATION_REQUEST_CODE = 567;
    private DrinkDao drinkDao;
    private SaveDao saveDao;
    //处理联网信息
    private long cutNet_stra_time = 0;
    private long cutNet_end_time = 0;
    private long cutNet_index_time = 48 * 60 * 60 * 1000; //72 小时时间间隔 测试 3分钟
    private boolean upwater_flag = false; //上传喝水标记
    private String msg_weather, //天气
            msg_dringk, //饮水
            msg_waring; //警告
    List<RequestRecord>  list_play=new ArrayList<>(); //视频列表
    List<RequestRecord>  list_priority=new ArrayList<>(); //优先视频列表
    private int play_index = 0;  //播放位置
    private int priority_index = 0;//优先级位置
 private AvdDao avd_versionDao;//广告版本
private   PlayDao playDao; //播放记录
private RequestDao reDao; //请求记录
 private  boolean water_flag=false; //是否是接水过程中
 private  boolean upplay_flag=false; //是否已经上传播放数据
 private  boolean all_or_tody_flag=false; //是否上传所有数据

 private  PlayRecord play=null; //播放记录
 private  String zong_shui="0"; //水总量
  private  String zong_number="0"; //饮水总次数

    // DemoPushService.class 自定义服务名称, 核心服务
    //private Class userPushService = DemoPushService.class;
    private int net_number=0;

    private  boolean cup_flag=true; //是否绑定杯子

    /**
     * 数据库初始化
     */
private   void  initDao(){
    drinkDao = new DrinkDao(this);
    saveDao = new SaveDao(this);
    avd_versionDao =new AvdDao(this);
    playDao=new PlayDao(this);
    reDao=new RequestDao(this);
    initVersion(); //初始化版本库
new  Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        String time = DateTimeUtil.getTime();
        updateApk();
        try {
            List<AvdVersion> period = avd_versionDao.query("period", time);
            if(period==null||period.size()==0){
                Log.i(TAG, "播网络: ");
                getTomorrow(time,"1"); //今天广告数据获取
            }else {
                Log.i(TAG, "播本地: ");
                disNetGetPlayList();  //播放本地视频
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
},10*1000);



}

    /**
     * 初始化版本信息
     */
    private void initVersion() {
        SaveInfo info= new SaveInfo();
        info.setId(1);
        info.setBarcode("1");
        info.setDevice("1");
        info.setPwd("1");
        try {
            SaveInfo qur_b = saveDao.queryById("id", "1");
            if(qur_b==null){
                saveDao.save(info);
            }else {
                SaveInfo bar = saveDao.queryById("id", "1");
                ShareTool.saveInfo(MainActivity.this,"bar_pwd",bar.getPwd().equals("1")?"":bar.getPwd());
                ShareTool.saveInfo(MainActivity.this,"bar_code",bar.getBarcode().equals("1")?"":bar.getBarcode());
                ShareTool.saveInfo(MainActivity.this,"scode",bar.getDevice().equals("1")?"":bar.getDevice());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
//    public void initList() {
////        list_sd.add(URLConstant.HOST+"/upfiles/files/201711/0315096723265607.mp4");
////        list_sd.add(URLConstant.HOST+"/upfiles/files/201709/1215051911249187.mp4");
////        list_sd.add(URLConstant.HOST+"/upfiles/files/201709/1215051957482178.mp4");
////        list_sd.add(URLConstant.HOST+"/upfiles/files/201709/2415062367687889.mp4");
////        list_sd.add(URLConstant.HOST+"/upfiles/files/201711/2015111652063984.mp4");
//        list_sd.add(URLConstant.HOST + "/upfiles/files/201711/1015102856461730.mp4");
////        list_sd.add(URLConstant.HOST+"/upfiles/files/201711/1015103051547994.mp4");
//        list_sd.add(URLConstant.HOST + "/upfiles/files/201712/1215130637237124.mp4");
////        list_sd.add(URLConstant.HOST+"/upfiles/files/201712/1815135766962581.mp4");
//        //       list_sd.add(URLConstant.HOST+"/upfiles/files/201712/1815135750187069.mp4");
////        list_sd.add(URLConstant.HOST+"/upfiles/files/201712/2515141676706585.mp4");
//        for (int i = 0; i < list_sd.size(); i++) {
//            headers.put(i + "", list_sd.get(i));
//        }
//    }



    /**
     * 检查网络状态
     */
    public boolean ping() {
        //   String result = null;
        BufferedReader in = null;
        InputStream input = null;
        try {
            String ip = "wys.app.ctopus.com";
            Process p = Runtime.getRuntime().exec("ping -c 1 -w 100 " + ip);// ping1次
            // 读取ping的内容，可不加。
            input = p.getInputStream();
            in = new BufferedReader(new InputStreamReader(input));
            // PING的状态
            int status = p.waitFor();
            if (status == 0) {
                //     result = "successful~";
                netHandler.sendEmptyMessage(1);
                return true;
            }
        } catch (IOException e) {
            // result = "failed~ IOException";
        } catch (InterruptedException e) {
            // result = "failed~ InterruptedException";
        } finally {
            //  Log.i("TTT", "result = " + result);

            try {
                if (in != null) {
                    in.close();
                }
                if (input != null) {
                    input.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        netHandler.sendEmptyMessage(0);
        return false;
    }

    /**
     * 上传
     */
    private Handler upHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    String str = (String) msg.obj;
                    try {
                        JSONObject json = new JSONObject(str);
                        String code = json.optString("code");
                        String msg1 = json.optString("msg");
                        if (code.equals("100")) {
                            upwater_flag = false;
                            try {
                                int delete = drinkDao.delete(drinkDao.queryAll());
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                        } else {
                            ToastTool.toast(msg1);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;

            }


            return false;
        }
    });


    /**
     * 联网
     */
    private Handler netHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            switch (msg.what) {
                case 1:  //有网
                    haveNet = true;
                    cutNet_stra_time = 0;
                    //   ToastTool.toast("有网");
                    break;
                case 0: //没网
                    if (cutNet_stra_time == 0) {
                        cutNet_stra_time = System.currentTimeMillis();
                    }
                    haveNet = false;
                    upwater_flag = true; //没网 开启上传
                    //更新日期
                    all_or_tody_flag=true;
                    //播放视频
                    //  ToastTool.toast("没网");
                    break;
            }
            return false;
        }
    });

    /**
     * 处理USB读写
     * -1 读出现异常
     * 0没有读取到数据
     * 1 读取大数据
     */
    private Handler usbHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            String str = msg.obj.toString();
            switch (msg.what) {
                case -1:
                    ToastTool.toast(str);
                    break;
                case 0:
                    ToastTool.toast(str);
                    break;
                case 1:
                    try {
                        famtStr(str);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

            }
            return false;
        }
    });
    /**
     * 处理天气
     */
    private Handler weatherHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            switch (msg.what) {

                case 1:
                    Weather wea = (Weather) msg.obj;
                    String code = wea.getCode();
                    String ms = wea.getMsg();
                    if (code.equals("100")) {
                        Weather.ResultBean result = wea.getResult();
                        String city = result.getCity();
                        String day_weather = result.getDay_weather();
                        String add_time = result.getAdd_time();
                        String day_air = result.getDay_air();
                        String night_air = result.getNight_air();
                        msg_weather = add_time + "  " + city + "  " + day_weather + "  " + night_air + "/" + day_air;
                        mainMsg.setText(msg_weather);
                        mainHead.setVisibility(View.INVISIBLE);

                    } else {
                        ToastTool.toast(ms);
                    }

                    break;

            }
            return false;
        }
    });


    /**
     * @param str
     * 处理口令
     */
    private String msg_send = "";
    private boolean haveNet = true;

    public void famtStr(String str) {
        Log.i(TAG, "famtStr: ----" + str);
        if (str.contains("AT+YR")) {
            //  ToastTool.toast("饮水机给平板发送AT+YR");
            // conInorOut(2);
        } else if (str.contains("AT+QS")) {
            JumpTool.jump(MainActivity.this, HuanTongActivity.class);

        } else if (!str.contains("AT+OK")) {
            //按等号分成两部分
            if (str.length() > 0 && str.contains("AT+XDRD")) {
                //消毒

                msg_send = "AT+XD";
                writeToUSb(msg_send);
                //通知服务端
                // shajun();
            } else if (str.length() > 0) {
                String kouling = "";
                String content = "";
                if (str.contains("=")) {
                    String[] split = str.split("=");
                    String code = split[0];
                    content = split[1];
                    int index = code.indexOf("AT") == -1 ? code.indexOf("T") : code.indexOf("AT");
                    if (index == -1) {
                        return;
                    }
                    kouling = code.indexOf("AT") == -1 ? "A" + code.substring(index).trim() : code.substring(index).trim();
                } else {
                    kouling = str.trim();
                }

                Log.i(TAG, "famtStr:口令: " + kouling + "---内容" + content);

                switch (kouling) {
                    case "AT+DSSC": //每钟上传一次
                        //没网--处理日期更新 视频播放
                        // 获取网络状态

                        net_number++;
                    if(net_number>=5) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                ping();
                            }
                        }).start();
                        net_number=0;
                    }
                        if (!haveNet) {
                            mLocationClient.stopLocation();
                            if(list_play.size()<1){
                                disNetGetPlayList();
                            }

                        } else {
                            if (mLocationClient != null) {
                                mLocationClient.stopLocation();
                                mLocationClient.startLocation();
                            }
                          // 更新版本
                            addapk_time++;
                            if(addapk_time>=getapk_time){
                                updateApk();
                                addapk_time=0;
                            }
                            //-----------------------------------
                        //每天 1点到3 点 更新明天数据
                         Calendar calendar =Calendar.getInstance();
                            long timeInMillis = calendar.getTimeInMillis()+24*60*60*1000;
                            calendar.setTimeInMillis(timeInMillis);
                            final String time = DateTimeUtil.getTime(calendar);
                            int mint = DateTimeUtil.getMint();
                            boolean upTime = DateTimeUtil.getUpTime(13, 15);
                            Log.i(TAG, "是否在更新时间段: "+upTime);
                            if((!isAvdVersion(time))&&upTime){
                                Random r= new Random();
                                int i = r.nextInt(50)+1;
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        getTomorrow(time,"0");
                                    }
                                },i*60*1000);
                                Log.i(TAG, "更新: ");
                            }else {
                                Log.i(TAG, "未更新: ");
                            }
                           //-------------------------------------
                            //发送心跳
                            heart_time++;
                            if(heart_time>=10){
                                sendHeart();
                                heart_time=0;
                            }
                            //------------------------------------------------
                            //上传数据
                            upPlayRecord();
                        }
                        String[] split2 = content.split(",");
                        String content_1 = "";
                        String content_2 = "";
                        String content_3 = "";
                        if (split2.length > 2) {
                            content_1 = preseStr(split2[0]);
                            content_2 = preseStr(split2[1]);
                            content_3 = preseStr(split2[2]);
                        } else {
                            content_1 = preseStr(split2[0]);
                            content_2 = preseStr(split2[1]);
                        }
                        int i1 = content.lastIndexOf(">");
                        String substring1 = content.substring(1, i1);
                        int leftIndex = substring1.indexOf("<");
                        int rightIndex = substring1.indexOf(">");
                        float parseInt = 0;
                        if (content_2 != null && isNumeric(content_2)) {
                            parseInt = Float.parseFloat(content_2);
                        } else {
                            parseInt = 0;
                        }

                        //没有总饮水量------------------------------------------------
                        int i = (int) (parseInt / 1000);
                        Log.i(TAG, "famtStr: 剩余水量" + i + "====" + content_1);
                        //给服务器传送剩余水量等信息
                        waterYield(parseInt + "");
                        break;
                    case "AT+CSEND":
                        water_flag =false; //喝水标记

                        if (msg_send.equals("AT+XD") || msg_send.equals("AT+PS")) {
                            return;
                        }
                        int leftIndex1 = content.indexOf("<");
                        int rightIndex1 = content.lastIndexOf(">");
                        if (rightIndex1 != -1 && leftIndex1 != -1) {
// 等号后边 处理
                            String content_11 = content.substring(leftIndex1);
//按,号分割数据
                            String[] split1 = content_11.split(",");
                            //判断是饮水信息还是系统信息
                            int length = split1.length;
                            if (length == 4) {  //饮水
                                String s_shuibei = preseStr(split1[0]);
                                String s_shuiwen = preseStr(split1[1]);
                                String s_shuizhi = preseStr(split1[2]);
                                String s_shuiliang = preseStr(split1[3]);
                                Log.i(TAG, "famtStr:水杯: " + s_shuibei + "--水温:" + s_shuiwen + "--水质:" + s_shuizhi + "--水量:" + s_shuiliang);
                                //获取水温  愣是72小时未接建议排水
                                if (s_shuiwen != null && s_shuiwen.length() > 0) {
                                    lengshuiPaishui(s_shuiwen);
                                }
                                //  String str_msg="本次饮水数据:水杯: "+s_shuibei+",水温:"+s_shuiwen+",水质:"+shuizhiToString(s_shuizhi)+",水量:"+s_shuiliang;
                                //提交喝喝水数据
                                if (haveNet) {
                                    submit_Water(s_shuibei, s_shuizhi, s_shuiliang, s_shuiwen);
                                    //更新 总水量
                                    double v = Double.parseDouble(s_shuiliang);
                                    double v1=0;
                                    if(zong_shui.length()>0){
                                        v1 = Double.parseDouble(zong_shui);
                                    }
                                    long round = Math.round(v + v1);
                                    if(cup_flag){
                                    //更新单次饮水量
                                    msg_dringk = "饮水次数:" + zong_number + "    水量:" + s_shuiliang+ "    水质:" +shuizhiToString(s_shuizhi )+ "    总饮水量:" + round;
                                    mainMsg.setText(msg_dringk);
                                    }else {
                                        mainMsg.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.white));
                                        mainMsg.setText("");
                                    }
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            mainMsg.setText(msg_weather);
                                            mainHead.setVisibility(View.INVISIBLE);
                                        }
                                    }, 4000);


                                } else {
                                    try {
                                        Drink drin = new Drink();
                                        Calendar c = Calendar.getInstance();
                                        drin.setDatetime(DateTimeUtil.getTime(c));
                                        drin.setQuantity(s_shuiliang);
                                        drin.setTemperature(s_shuiwen);
                                        drin.setWater_quality(s_shuizhi);
                                        drin.setCup_num(s_shuibei);
                                        String bar_code = ShareTool.getInfo(MainActivity.this, "bar_code");
                                        drin.setBar_code(bar_code);
                                        drinkDao.save(drin);
                                    } catch (SQLException e) {
                                        e.printStackTrace();
                                    }
                                }
                            } else if (length == 5) { //系统
                                //更新水量
                                String s = split1[0];
                                int left = s.indexOf("<");
                                int right = s.indexOf(">");
                                String substring = s.substring(left + 1, right);
                                parseInt = Integer.parseInt(substring);
                                i = (int) (parseInt / 1000);
                                Log.i(TAG, "famtStr: 剩余水量" + i);
                                //给服务器传送剩余水量等信息
                                waterYield(parseInt + "");
                            }
                        }
                        break;
                    case "AT+CSSTART":
                        water_flag=true; //喝水标记
                        ls_start_time = System.currentTimeMillis();
                        ShareTool.saveInfo(MainActivity.this, "ls_start_time", ls_start_time + "");
                        cutNet_end_time = System.currentTimeMillis();
//                        if(list_priority.size()>0){
//                            if(priority_index>=list_priority.size()){
//                                priority_index=0;
//                            }
//                            mVideoView.setVideoPath(list_play.get(priority_index).getUrl());
//                            mVideoView.start();
//                            priority_index++;
//                        }
                        //接水请求
                        if (haveNet) {
                            postDrinkWater(content);
                            if (upwater_flag) {   //来往后上传数据
                                uplodeFile();
                            }

                        } else {
                            //断网超过48小时
                            if (cutNet_end_time - cutNet_stra_time >= cutNet_index_time) {
                                msg_waring = "网络连接异常，请检查网络；断网已超过48小时，暂停使用";
                                mainMsg.setText(msg_waring);
                                mainMsg.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.read));
                                msg_send = "AT+STOP";
                                writeToUSb(msg_send);
                            }else {
                                msg_waring = "网络连接异常";
                                mainMsg.setText(msg_waring);
                                mainMsg.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.read));
                            }
                        }
                        break;
                    case "AT+XDSTOP":
                        msg_send = "AT+XDSTOP";
                        ToastTool.toast("消毒结束AT+XDSTOP");
                        break;
                    case "AT+PSSTOP":

                        msg_send = "AT+PSSTOP";
                        //  }
                        ToastTool.toast("排水结束AT+XDSTOP");
                        break;
                    case "AT+WARN":
                        int last_k = content.indexOf(">");
                        String warn = content.substring(1, last_k);
                        Log.i(TAG, "famtStr: " + warn.equals("1") + "==" + warn);
                        //提交警告码
                        subWarn(warn);
                        break;

                }
            }
        } else {
            switch (msg_send) {
                case "AT+HT": //处理换桶成功逻辑
                    ToastTool.toast("换桶成功");
                    //换桶停止音效
                    //  stopSound();
                    break;
                case "AT+STOP":
                    //  conInorOut(5);
                    break;
                case "AT+CSH":
                    ToastTool.toast("初始化成功");
                    msg_send = "AT+PS";
                    writeToUSb(msg_send);
                    break;
                case "AT+PS":
                    ToastTool.toast("排水成功");
                    msg_send = "AT+LBKPS";
                    writeToUSb(msg_send);
                    break;
                case "AT+LBKPS":
                    ToastTool.toast("凉白开排水成功");
                    break;
                case "AT+CS3":
                    ToastTool.toast("设置成功");
                    break;


            }

        }
    }

    /**
     * @param s_shuibei
     * @param s_shuizhi
     * @param s_shuiliang 喝水数据提交
     */
    private void submit_Water(String s_shuibei, String s_shuizhi, String s_shuiliang, String s_shuiwen) {

        Map<String, String> params = new HashMap<>();
        String bar_code = ShareTool.getInfo(MainActivity.this, "bar_code");
        try {
            if (bar_code.length() < 1) {
                SaveInfo bar = saveDao.queryById("id", "1");
                if(bar!=null) {
                    bar_code = bar.getBarcode();
                }else {
                    bar_code ="";
                }

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        params.put("bar_code", bar_code == null ? "" : bar_code);
        params.put("cup_num", s_shuibei);
        params.put("water_quality", s_shuizhi);
        params.put("quantity", s_shuiliang);
        params.put("temperature", s_shuiwen);
        //     yinshui_liang.setText(s_shuiliang+"");
        //   yinshui_wen.setText(s_shuiwen+"");
        // TODO: 2017/7/26   水质
        //      String s_zhi = shuizhiToString(s_shuizhi);
        //   yinshui_zhi.setText(s_zhi);
        // TODO: 2017/7/26   时间
        Calendar calendar = Calendar.getInstance();
        String time = DateTimeUtil.getTime(calendar);
        //  yinshui_time.setText(time);
        String path = okTool.getPath(URLConstant.DEVICE_THISDRINKWATER, params);
        okTool.doGet(path, new StringCallback() {
            @Override
            public void onBeforeRequest(Request request) {
            }

            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onSuccess(Response response, String t) {
                try {
                    JSONObject json = new JSONObject(t);
                    String msg = json.optString("msg");
                    String code = json.optString("code");
                    if (code.equals("100")) {
                    } else {
                        ToastTool.toast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Response response, String errorMsg) {
            }
        });
    }
    private void uplodeFile() {
        if (upwater_flag) {
            String path = Environment.getExternalStorageDirectory() + "/WAT.db";
            okTool.uploadFile(path, upHandler);
        }
    }

    /**
     * @param content 水杯号
     *                <p>
     *                喝水请求
     */
    private void postDrinkWater(String content) {
        String at = content;
        if (content.contains("AT")) {
            at = content.substring(0, content.indexOf("AT"));
        }
        String bar_code = ShareTool.getInfo(MainActivity.this, "bar_code");
        try {
            if (bar_code.length() < 1) {
                SaveInfo bar = saveDao.queryById("id", "1");
                if(bar!=null) {
                    bar_code = bar.getBarcode();
                }else {
                    bar_code ="";
                }

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String path = URLConstant.HOST + URLConstant.DEVICE_DRINKWATER + "bar_code=" + bar_code + "&number=" + at;
        okTool.doGet(path, new MyHttpCallback<DringkWater>() {
            @Override
            public void onBeforeRequest(Request request) {
            }

            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onSuccess(Response response, DringkWater dringkWater) {
                String code1 = dringkWater.getCode();
                String msg = dringkWater.getMsg();
                if (code1.equals("100")) {
                    cup_flag=true;
                    List<DringkWater.ResultBean> result_list = dringkWater.getResult();
                    if (result_list != null && result_list.size() > 0) {
                        DringkWater.ResultBean result = result_list.get(0);
                        //设置左侧信息
                        String today_num = result.getToday_num();
                        String quantity = result.getQuantity();
                        String water_quality = result.getWater_quality();
                        String today_water = result.getToday_water();
                        String headimg = result.getHeadimg();
                        msg_dringk = "饮水次数:" + today_num + "    水量:--"  + "    水质:" +shuizhiToString(water_quality )+ "    总饮水量:" + today_water;
                        mainMsg.setText(msg_dringk);
                        mainMsg.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.white));
                        Glide.with(getApplicationContext()).load(URLConstant.HOST + headimg).into(mainHead);
                        mainHead.setVisibility(View.VISIBLE);
                        zong_shui=today_water;
                        zong_number=today_num;
                    }else {
                        msg_dringk = "饮水次数:" + 1 + "    水量:--"  + "    水质:优" + "    总饮水量:--" ;
                        mainMsg.setText(msg_dringk);
                        mainMsg.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.white));
                    }


                } else if (code1.equals("404")) {
                    msg_send = "AT+STOP";
                    writeToUSb(msg_send);
                    //  没有数据处理;
                    if (haveNet) {
                        msg_waring = "杯子号未绑定，请下载APP并绑定杯子号";
                        mainMsg.setText(msg_waring);
                        mainMsg.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.read));
                    }

                } else {
                //    ToastTool.toast(msg);
                    mainMsg.setText(msg);
                    mainMsg.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.read));
                    cup_flag=false;
                }
            }

            @Override
            public void onError(Response response, String errorMsg) {
            }


















































































































































        });
    }

    /**
     * @param str
     * @return 处理饮水数据
     */
    private String preseStr(String str) {
        int left = str.indexOf("<");
        int right = str.indexOf(">");
        return str.substring(left + 1, right);

    }

    /**
     * @param warn
     * 警告码
     */
    Dialog warnDialog;

    private void subWarn(String warn) {
        Map<String, String> params = new HashMap<>();
        String bar_code = ShareTool.getInfo(MainActivity.this, "bar_code");
        try {
            if (bar_code.length() < 1) {
                SaveInfo bar = saveDao.queryById("id", "1");
                if(bar!=null) {
                    bar_code = bar.getBarcode();
                }else {
                    bar_code ="";
                }

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        params.put("bar_code", bar_code);
        params.put("error_code", warn);
        String path = okTool.getPath(URLConstant.DEVICE_DEVICETROUBLE, params);
        okTool.doGet(path, new MyHttpCallback<WarnCode>() {
            @Override
            public void onBeforeRequest(Request request) {
            }

            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onSuccess(Response response, WarnCode warnCode) {
                String code1 = warnCode.getCode();
                String msg = warnCode.getMsg();
                List<String> result = warnCode.getResult();
                if (code1.equals("100")) {
                    if (result != null && result.size() > 0) {
                        if (warnDialog != null && warnDialog.isShowing()) {
                            warnDialog.dismiss();
                        }
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle("警告!");
                        builder.setCancelable(false);
                        String str = "";
                        for (int i = 0; i < result.size(); i++) {
                            str += result.get(i) + "\n";
                        }
                        builder.setMessage(str);
                        builder.setPositiveButton("已处理", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //  dialog.dismiss();
                                //取消警告
                                msg_send = "AT+CZ";
                                writeToUSb(msg_send);
                                cancleWarn(dialog);
                            }
                        });
                        warnDialog = builder.create();

                        warnDialog.show();
                    }


                }

            }

            @Override
            public void onError(Response response, String errorMsg) {

            }
        });
    }

    /**
     * 取消警告
     *
     * @param dialog
     */
    private void cancleWarn(DialogInterface dialog) {

        Map<String, String> params = new HashMap<>();
        String bar_code = ShareTool.getInfo(MainActivity.this, "bar_code");
        params.put("bar_code", bar_code);
        String path = okTool.getPath(URLConstant.DEVICE_DEVICENORMAL, params);
        okTool.doGet(path, new StringCallback() {
            @Override
            public void onBeforeRequest(Request request) {

            }

            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onSuccess(Response response, String t) {
                try {
                    JSONObject json = new JSONObject(t);
                    String code = json.optString("code", "-1");

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onError(Response response, String errorMsg) {

            }
        });


    }

    /**
     * @param s_shuiwen 72小时未接冷水
     */
    private long ls_start_time = 0;

    private void lengshuiPaishui(String s_shuiwen) {
        int i = Integer.parseInt(s_shuiwen);
        String ls_start = ShareTool.getInfo(MainActivity.this, "ls_start_time");
        ls_start = ls_start.length() > 0 ? ls_start : "0";
        long l_time = Long.parseLong(ls_start);
        if (i < 99) {  //喝温水
            long cha = System.currentTimeMillis() - l_time;
            if (cha >= 72 * 60 * 60 * 1000) { //喝温水间隔大于72小时
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("建议排水");
                builder.setMessage("温水72小时未接是否排水?");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ToastTool.toast("喝水间隔大于72小时了");
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });


                builder.show();


            }

        }
    }

    /**
     * 传递饮水量信息
     * 经纬度
     * 剩余水量
     * 滤芯
     */



    private void waterYield(String shuiliang) {

        Map<String, String> params = new HashMap<>();
        String bar_code = ShareTool.getInfo(MainActivity.this, "bar_code");
        try {
            if (bar_code.length() < 1) {
                SaveInfo bar = saveDao.queryById("id", "1");
                if(bar!=null) {
                    bar_code = bar.getBarcode();
                }else {
                    bar_code ="";
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        params.put("bar_code", bar_code);
        String lat = ShareTool.getInfo(MainActivity.this, "lat");
        String lon = ShareTool.getInfo(MainActivity.this, "lon");
        String dev = ShareTool.getInfo(MainActivity.this, "dev");
        params.put("lat", lat);
        params.put("lng", lon);
        params.put("water_yield", shuiliang);
        params.put("device_token", dev);
        String path = okTool.getPath(URLConstant.DEVICE_WATERYIELD, params);
        okTool.doGet(path, new StringCallback() {
            @Override
            public void onBeforeRequest(Request request) {

            }

            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onSuccess(Response response, String t) {
                try {
                    JSONObject json = new JSONObject(t);
                    String msg = json.optString("msg");
                    String code = json.optString("code");
                    if (code.equals("100")) {
                        Log.i(TAG, "日常信息" + msg);
                    } else {
                        ToastTool.toast(msg);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Response response, String errorMsg) {

            }
        });
    }

    /**
     * @param s 往平板写数据
     */
    public void writeToUSb(String s) {
        byte[] data = s.getBytes();
        UsbTool.getInstance().writeToUsb(data);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WindowTool.hideBottomUIMenu(this);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
//        String sHA1 = sHA1(this);
//        Log.i(TAG, "onCreate: " + sHA1);
        initDao();
        mainHead.setVisibility(View.INVISIBLE);
//    sdk  权限获取
        isPermissionOK();
        setOptions(1);
        mVideoView.setOnInfoListener(mOnInfoListener);
        mVideoView.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
        mVideoView.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
        mVideoView.setOnCompletionListener(mOnCompletionListener);
        mVideoView.setOnErrorListener(mOnErrorListener);
        mVideoView.setOnVideoFrameListener(mOnVideoFrameListener);
        mVideoView.setOnAudioFrameListener(mOnAudioFrameListener);
        //  mVideoView.setDisplayAspectRatio(PLVideoView.ASPECT_RATIO_ORIGIN); //原始尺寸
      //  mVideoView.setDisplayAspectRatio(PLVideoView.ASPECT_RATIO_FIT_PARENT);//适应屏幕
        ViewTreeObserver vto = mainReal.getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                int height = mainReal.getMeasuredHeight();
                int width = mainReal.getMeasuredWidth();
                mVideoView.setLayoutParams(new RelativeLayout.LayoutParams(width,height));
                return true;
            }
        });

     //   Log.i(TAG, "onCreate: "+mainReal.getWidth()+"---"+mainReal.getHeight());

        //  mVideoView.setDisplayAspectRatio(PLVideoView.ASPECT_RATIO_PAVED_PARENT);//全屏铺满
        //    mVideoView.setDisplayAspectRatio(PLVideoView.ASPECT_RATIO_16_9); //16:9
        //   mVideoView.setDisplayAspectRatio(PLVideoView.ASPECT_RATIO_4_3);//4:3
        mVideoView.setLooping(getIntent().getBooleanExtra("loop", false));

        //这里以ACCESS_COARSE_LOCATION为例   定位权限获取
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    WRITE_COARSE_LOCATION_REQUEST_CODE);//自定义的code
        }
        getGps();

    }

    @Override
    protected void onStart() {
        super.onStart();
        WindowTool.hideBottomUIMenu(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mIsActivityPaused = false;
        mVideoView.start();
        UsbTool.getInstance().setHandler(usbHandler);
        UsbTool.getInstance().openUsbDevice(MainActivity.this);
        WindowTool.hideBottomUIMenu(this);
     // PushManager.getInstance().initialize(this, userPushService);
        // 注册 intentService 后 PushDemoReceiver 无效, sdk 会使用 DemoIntentService 传递数据,
        // AndroidManifest 对应保留一个即可(如果注册 DemoIntentService, 可以去掉 PushDemoReceiver, 如果注册了
        // IntentService, 必须在 AndroidManifest 中声明)
    //    PushManager.getInstance().registerPushIntentService(this, DemoIntentService.class);

   //     String clientid = PushManager.getInstance().getClientid(this);
    //    Log.d(TAG, "clientid=" + clientid);

     //   PushManager manager = PushManager.getInstance();
     //   boolean flag = manager.bindAlias(this, "15153519007");
//        if (flag) {
//            Log.d(TAG, "绑定成功");
//        } else {
//            Log.d(TAG, "绑定失败");
//        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mToast = null;
        mIsActivityPaused = true;
        mVideoView.pause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            UsbTool.getInstance().unRegist();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mVideoView.stopPlayback();

    }


    /**
     * @return sdk 权限
     */
    public boolean isPermissionOK() {
        PermissionChecker checker = new PermissionChecker(this);
        boolean isPermissionOK = Build.VERSION.SDK_INT < Build.VERSION_CODES.M || checker.checkPermission();
        if (!isPermissionOK) {
            Toast.makeText(this, "有些权限不被批准！！！", Toast.LENGTH_SHORT).show();
        }
        return isPermissionOK;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);


        //可在此继续其他操作。
    }

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {

        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
//可在其中解析amapLocation获取相应内容。
                    //  Log.i(TAG, "onLocationChanged: " + amapLocation.getLatitude() + "---" + amapLocation.getLongitude());
                    String the_city = amapLocation.getCity();
                    //    ToastTool.toast("onLocationChanged: " + the_city);
                    getWeather(the_city);
                    ShareTool.saveInfo(MainActivity.this, "lat", amapLocation.getLatitude() + "");
                    ShareTool.saveInfo(MainActivity.this, "lon", amapLocation.getLongitude() + "");
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("tag", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };


    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    //定位相关
    private void getGps() {
//初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
//设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
        AMapLocationClientOption option = new AMapLocationClientOption();
        mLocationOption.setHttpTimeOut(20000);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        if (null != mLocationClient) {
            mLocationClient.setLocationOption(option);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
        mLocationOption.setOnceLocation(true);
    }

    /**
     * @param codecType 设置7牛云
     */
    private void setOptions(int codecType) {
        AVOptions options = new AVOptions();
        // // 准备超时时间，包括创建资源、建立连接、请求码流等，单位是 ms// 默认值是：无
        options.setInteger(AVOptions.KEY_PREPARE_TIMEOUT, 10 * 1000);
        // 1 -> hw codec enable, 0 -> disable [recommended]
        options.setInteger(AVOptions.KEY_MEDIACODEC, AVOptions.MEDIA_CODEC_AUTO);
        options.setInteger(AVOptions.KEY_LIVE_STREAMING, mIsLiveStreaming ? 1 : 0);
        boolean disableLog = getIntent().getBooleanExtra("disable-log", false);
        options.setInteger(AVOptions.KEY_LOG_LEVEL, disableLog ? 5 : 0);
        boolean cache = getIntent().getBooleanExtra("cache", false);
        //   if (!mIsLiveStreaming && cache) {
        options.setString(AVOptions.KEY_CACHE_DIR, Config.DEFAULT_CACHE_DIR);
        //   }
        boolean vcallback = getIntent().getBooleanExtra("video-data-callback", false);
        if (vcallback) {
            options.setInteger(AVOptions.KEY_VIDEO_DATA_CALLBACK, 1);
        }
        boolean acallback = getIntent().getBooleanExtra("audio-data-callback", false);
        if (acallback) {
            options.setInteger(AVOptions.KEY_AUDIO_DATA_CALLBACK, 1);
        }
        mVideoView.setAVOptions(options);
    }

    private String TAG = "tag";
    private PLMediaPlayer.OnInfoListener mOnInfoListener = new PLMediaPlayer.OnInfoListener() {
        @Override
        public boolean onInfo(PLMediaPlayer plMediaPlayer, int what, int extra) {
            //  Log.i(TAG, "OnInfo, what = " + what + ", extra = " + extra);
            switch (what) {
                case PLMediaPlayer.MEDIA_INFO_BUFFERING_START://开始缓冲

                    break;
                case PLMediaPlayer.MEDIA_INFO_BUFFERING_END://停止缓冲
                    break;
                case PLMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START://第一帧视频已成功渲染
                    //   showToastTips("first video render time: " + extra + "ms");
                    break;
                case PLMediaPlayer.MEDIA_INFO_AUDIO_RENDERING_START://第一帧音频已成功播放
                    Log.i(TAG, "第一帧音频已成功播放: "+play_index+"------"+priority_index);
                    RequestRecord requestRecord=null;
                    if(!water_flag){ //没接水
                        if(play_index>=list_play.size()){
                            play_index=0;
                        }
                        requestRecord = list_play.get(play_index);
                    }else {
                        if(priority_index>=list_priority.size()){
                            priority_index=0;
                        }
                        requestRecord=list_priority.get(priority_index);
                    }
                    play=new PlayRecord();
                    int start =(int)(System.currentTimeMillis() / 1000);
                    play.setStart(start);
                    play.setPeriod(requestRecord.getPeriod());
                    play.setPlay_id(requestRecord.getId());

                    break;
                case PLMediaPlayer.MEDIA_INFO_VIDEO_FRAME_RENDERING://视频帧的时间戳
                    // Log.i(TAG, "video frame rendering, ts = " + extra);
                    break;
                case PLMediaPlayer.MEDIA_INFO_AUDIO_FRAME_RENDERING://音频帧的时间戳
                    // Log.i(TAG, "audio frame rendering, ts = " + extra);
                    break;
                case PLMediaPlayer.MEDIA_INFO_VIDEO_GOP_TIME://获取视频的I帧间隔
                    //  Log.i(TAG, "Gop Time: " + extra);
                    break;
                case PLMediaPlayer.MEDIA_INFO_SWITCHING_SW_DECODE://硬解失败，自动切换软解
                    // Log.i(TAG, "Hardware decoding failure, switching software decoding!");
                    break;
                case PLMediaPlayer.MEDIA_INFO_METADATA://读取到 metadata 信息
                   // Log.i(TAG, mVideoView.getMetadata().toString());
                    break;
                case PLMediaPlayer.MEDIA_INFO_VIDEO_BITRATE://视频的码率统计结果
                case PLMediaPlayer.MEDIA_INFO_VIDEO_FPS://视频的帧率统计结果
                    updateStatInfo();
                    break;
                case PLMediaPlayer.MEDIA_INFO_CONNECTED:	//连接成功
                    //  Log.i(TAG, "Connected !");
                    break;
                case PLMediaPlayer.MEDIA_INFO_VIDEO_ROTATION_CHANGED://获取到视频的播放角度
                    //  Log.i(TAG, "Rotation changed: " + extra);
                default:
                    break;
            }
            return true;
        }
    };
    private PLMediaPlayer.OnErrorListener mOnErrorListener = new PLMediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(PLMediaPlayer mp, int errorCode) {
            switch (errorCode) {
                case PLMediaPlayer.ERROR_CODE_IO_ERROR:
                    /**
                     * SDK will do reconnecting automatically
                     */
                    //  Log.e(TAG, "IO Error!");
                    try {
                        //保存播放记录
                        int end =(int)(System.currentTimeMillis() / 1000);
                        if(null!=play){
                            play.setStart(end);
                            play.setErr(1);
                            playDao.save(play);
                        }
                    }catch (SQLException e) {
                        e.printStackTrace();
                    }
                    return false;
                case PLMediaPlayer.ERROR_CODE_OPEN_FAILED:
                    showToastTips("没有打开播放器!");
                    break;
                case PLMediaPlayer.ERROR_CODE_SEEK_FAILED:
                    showToastTips("failed to seek !");
                    break;
                default:
                    showToastTips("未知错误!");
                    break;
            }
            finish();
            return true;
        }
    };
    private PLMediaPlayer.OnCompletionListener mOnCompletionListener = new PLMediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(PLMediaPlayer plMediaPlayer) {
           // showToastTips("播放完毕"+list_play.size());
            Log.i(TAG, "成功播放: "+play_index+"------"+priority_index);
            int end =(int)(System.currentTimeMillis() / 1000);
            play.setEnd(end);
            play.setErr(0);
            try {
                playDao.save(play); //保存播放记录
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if(!water_flag) {   //没接水播放
                play_index++;
                if (play_index >= list_play.size()) {
                    play_index = 0;
                }
                mVideoView.setVideoPath(list_play.get(play_index).getUrl());

            }else {   //接水播放
                if(list_priority.size()>0) {
                    if (priority_index >= list_priority.size()) {
                        priority_index = 0;
                    }
                    mVideoView.setVideoPath(list_priority.get(priority_index).getUrl());
                    priority_index++;
                }
            }
            mVideoView.setOnPreparedListener(new PLMediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(PLMediaPlayer plMediaPlayer, int i) {
                    mVideoView.start();
                }
            });

            if (!mIsLiveStreaming) {
                // mMediaController.refreshProgress();
            }
            //finish();
        }
    };
    private PLMediaPlayer.OnBufferingUpdateListener mOnBufferingUpdateListener = new PLMediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(PLMediaPlayer plMediaPlayer, int precent) {
            //  Log.i(TAG, "onBufferingUpdate: " + precent);
        }
    };

    private PLMediaPlayer.OnVideoSizeChangedListener mOnVideoSizeChangedListener = new PLMediaPlayer.OnVideoSizeChangedListener() {
        @Override
        public void onVideoSizeChanged(PLMediaPlayer plMediaPlayer, int width, int height) {
            //Log.i(TAG, "onVideoSizeChanged: width = " + width + ", height = " + height);
        }
    };

    private PLMediaPlayer.OnVideoFrameListener mOnVideoFrameListener = new PLMediaPlayer.OnVideoFrameListener() {
        @Override
        public void onVideoFrameAvailable(byte[] data, int size, int width, int height, int format, long ts) {
           //  Log.i(TAG, "onVideoFrameAvailable: " + size + ", " + width + " x " + height + ", " + format + ", " + ts);
        }
    };

    private PLMediaPlayer.OnAudioFrameListener mOnAudioFrameListener = new PLMediaPlayer.OnAudioFrameListener() {
        @Override
        public void onAudioFrameAvailable(byte[] data, int size, int samplerate, int channels, int datawidth, long ts) {
          // Log.i(TAG, "onAudioFrameAvailable: " + size + ", " + samplerate + ", " + channels + ", " + datawidth + ", " + ts);
        }
    };

//    private MediaController.OnClickSpeedAdjustListener mOnClickSpeedAdjustListener = new MediaController.OnClickSpeedAdjustListener() {
//        @Override
//        public void onClickNormal() {
//            // 0x0001/0x0001 = 2
//            mVideoView.setPlaySpeed(0X00010001);
//        }
//
//        @Override
//        public void onClickFaster() {
//            // 0x0002/0x0001 = 2
//            mVideoView.setPlaySpeed(0X00020001);
//        }
//
//        @Override
//        public void onClickSlower() {
//            // 0x0001/0x0002 = 0.5
//            mVideoView.setPlaySpeed(0X00010002);
//        }
//    };

    /**
     * @param context
     * @return
     * 判断联网状态
     */
    public static boolean isNetworkAvailable(Context context) {

        // 获得网络状态管理器
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null) {
            return false;
        } else {
            // 建立网络数组
            NetworkInfo[] net_info = connectivityManager.getAllNetworkInfo();

            if (net_info != null) {
                for (int i = 0; i < net_info.length; i++) {
                    // 判断获得的网络状态是否是处于连接状态
                    NetworkInfo networkInfo = net_info[i];
                    if (net_info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }


    private void updateStatInfo() {
        long bitrate = mVideoView.getVideoBitrate() / 1024;
        final String stat = bitrate + "kbps, " + mVideoView.getVideoFps() + "fps";
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
             //   Log.i(TAG, "码率: "+stat);
            }
        });
    }

    private void showToastTips(final String tips) {
        if (mIsActivityPaused) {
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mToast != null) {
                    mToast.cancel();
                }
                mToast = Toast.makeText(MainActivity.this, tips, Toast.LENGTH_SHORT);
                mToast.show();
            }
        });
    }

    protected Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what != MESSAGE_ID_RECONNECTING) {
                return;
            }
            if (mIsActivityPaused || !Utils.isLiveStreamingAvailable()) {
                finish();
                return;
            }
            if (!Utils.isNetworkAvailable(MainActivity.this)) {
                sendReconnectMessage();
                return;
            }
            //   mVideoView.setVideoPath(mVideoPath);
            //   mVideoView.start();
        }
    };

    private void sendReconnectMessage() {
        showToastTips("正在重连...");
        //  mLoadingView.setVisibility(View.VISIBLE);
        mHandler.removeCallbacksAndMessages(null);
        mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_ID_RECONNECTING), 500);
    }

    //获取SHA1的方法===================================================================
    public static String sHA1(Context context) {

        try {

            PackageInfo info = context.getPackageManager().getPackageInfo(

                    context.getPackageName(), PackageManager.GET_SIGNATURES);

            byte[] cert = info.signatures[0].toByteArray();

            MessageDigest md = MessageDigest.getInstance("SHA1");

            byte[] publicKey = md.digest(cert);

            StringBuffer hexString = new StringBuffer();

            for (int i = 0; i < publicKey.length; i++) {

                String appendString = Integer.toHexString(0xFF & publicKey[i])

                        .toUpperCase(Locale.US);

                if (appendString.length() == 1)

                    hexString.append("0");

                hexString.append(appendString);

            }

            return hexString.toString();

        } catch (PackageManager.NameNotFoundException e) {

            e.printStackTrace();

        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace();

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }


    private long lastonclickTime=0;//全局变量


    @OnClick({R.id.main_wifi, R.id.main_set, R.id.main_power})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.main_wifi:
                Intent it = new Intent();
                ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.wifi.WifiSettings");
                it.setComponent(cn);
                startActivity(it);
                break;
            case R.id.main_set:
                long time= SystemClock.uptimeMillis();//局部变量
                Log.i(TAG, "onViewClicked: "+time);
                if (time-lastonclickTime<=5000) {
                    ToastTool.toast("操作过快");
                }else {
                    lastonclickTime=time;
                   JumpTool.jump(this, SetActivity.class);
                }
                break;
            case R.id.main_power:
                //  JumpTool.jump(this, AlertActivity.class);
                break;
        }
    }


    /**
     * 获取天气
     */
    //天气
    private void getWeather(String city) {
        String bar_code = ShareTool.getInfo(MainActivity.this, "bar_code");
        try {
            if (bar_code.length() < 1) {
                SaveInfo bar = saveDao.queryById("id", "1");
                if(bar!=null) {
                    bar_code = bar.getBarcode();
                }else {
                    bar_code ="";
                }

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String path = URLConstant.HOST + URLConstant.THE_WEATHER + "city=" + city + "&bar_code=" + bar_code;

        okTool.doGet(path, new MyHttpCallback<Weather>() {
            @Override
            public void onBeforeRequest(Request request) {

            }

            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onSuccess(Response response, Weather weather) {
                Message msg = weatherHandler.obtainMessage(1, weather);
                weatherHandler.sendMessage(msg);
            }


            @Override
            public void onError(Response response, String errorMsg) {

            }
        });
    }

    /**
     * @param str
     * @return 是否为数字
     */
    public boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }


    /**
     * @param time
     * @param day
     * lastPeriod: 最后一次 期数 格式如 2018-01-24
    today : 1 或者 0 , 1为获取今天的数据，0 为获取明天的数据
     */
    private  void  getTomorrow(String time, final String day){
        Map<String, String> params = new HashMap<>();
        String url =URLConstant.AVD_HOST+URLConstant.GATEWAY_GETLIST;
        String bar_code = ShareTool.getInfo(MainActivity.this, "bar_code");
        try {
            if (bar_code.length() < 1) {
                SaveInfo bar = saveDao.queryById("id", "1");
                if(bar!=null) {
                    bar_code = bar.getBarcode();
                }else {
                    bar_code ="";
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        params.put("device",bar_code);
        System.currentTimeMillis();
        params.put("lastPeriod",time);
        params.put("today",day);
        okTool .doPost(url,params, new MyHttpCallback<Advertising>() {
            @Override
            public void onBeforeRequest(Request request) {
            }

            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(TAG, "获取数据失败onFailure: ----------------");
                disNetGetPlayList();  //播放本地视频

            }

            @Override
            public void onSuccess(Response response, Advertising advertising) {
               Log.i(TAG, "广告数据: "+advertising);
                boolean status = advertising.isStatus();
                if(status){
                    Advertising.DataBean data = advertising.getData();
                    //保存版本
                    String period = data.getPeriod();
                    AvdVersion avdVersion = new AvdVersion();
                    avdVersion.setPeriod(period);
                    try {
                        avd_versionDao.save(avdVersion);
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    List<Advertising.DataBean.PlayListBean> playList = data.getPlayList();
                    for (int i = 0; i <playList.size() ; i++) {
                        Advertising.DataBean.PlayListBean playListBean = playList.get(i);
                        RequestRecord  record=new RequestRecord();
                        record.setId(playListBean.getId());
                        record.setPeriod(data.getPeriod());
                        record.setPlaytime(playListBean.getPlaytime());
                        record.setPriority(playListBean.getPriority());
                        record.setUrl(playListBean.getUrl());
                        try {
                            int save = reDao.save(record);//保存列表记录
                           // Log.i(TAG, "保存数据: "+save);
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                        list_play.add(record);
                        if(playListBean.getPriority()==2){
                            list_priority.add(record);
                        }
                    }
                    if(day.equals("1")&&list_play.size()>0){   //今天数据
                        play_index=0;
                        mVideoView.setVideoPath(list_play.get(0).getUrl());
                        mVideoView.start();
                    }
//                    if(list_play.size()>0){ //保存数据
//                        try {
//                            reDao.save(list_play);
//                        } catch (SQLException e) {
//                            e.printStackTrace();
//                        }
//                    }
                }else {
                    String error = advertising.getError();
                    ToastTool.toast(error);
                }
            }
            @Override
            public void onError(Response response, String errorMsg) {

                Log.i(TAG, "获取数据onError: ----------------");
            }
        });
    }

    /**
     * 没网视频列表获取
     * //参数false表示降序，true表示升序。
     */
    private  void  disNetGetPlayList(){
        List<AvdVersion> avdVersions=new ArrayList<>();
        try {
           avdVersions = avd_versionDao.queryAll(true);
           if(avdVersions.size()>0) {
               AvdVersion avdVersion = avdVersions.get(avdVersions.size() - 1);
               String period = avdVersion.getPeriod();
               list_play = reDao.query("period", period);
               play_index=0;
               if(list_play.size()>0){  //存在列表
                   for (int i = 0; i < list_play.size(); i++) {
                       RequestRecord requestRecord = list_play.get(i);
                       if(requestRecord.getPriority()==2) {
                           list_priority.add(requestRecord);
                           priority_index=0;
                       }
                   }
                   play=new PlayRecord();
                   int start =(int)(System.currentTimeMillis() / 1000);
                   play.setStart(start);
                   play.setPeriod(list_play.get(0).getPeriod());
                   play.setPlay_id(list_play.get(0).getId());
                   mVideoView.setVideoPath(list_play.get(0).getUrl());
                   mVideoView.start();
               }

           }

        } catch (SQLException e) {
            e.printStackTrace();
        }


    }

    /**
     * 更新 版本
     */
    private   int  getapk_time=24*60*60;
    private   int  addapk_time=0;
    private void updateApk() {
        VersionTools intence = VersionTools.getIntence();

        intence.getVersionNumber(MainActivity.this);
    }

    /**
     * @return
     * 判断是否有明天版本
     */
    private  boolean isAvdVersion(String date){
        List<AvdVersion> avdVersions=new ArrayList<>();
        try {
            avdVersions = avd_versionDao.queryAll(true);
            if(avdVersions.size()>0){
                AvdVersion avdVersion = avdVersions.get(avdVersions.size() - 1);
                String period = avdVersion.getPeriod();
                Log.i(TAG, "isAvdVersion是否已经存在: "+date.equals(period));
              return date.equals(period);
            }else {
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 发送心跳
     */
    private  int heart_time=0;
    private  void sendHeart(){
        Map<String, String> params = new HashMap<>();
        String url =URLConstant.AD_JSON+URLConstant.GATEWAY_HEART;
        String bar_code = ShareTool.getInfo(MainActivity.this, "bar_code");
        try {
            if (bar_code.length() < 1) {
                SaveInfo bar = saveDao.queryById("id", "1");
                if(bar!=null) {
                    bar_code = bar.getBarcode();
                }else {
                    bar_code ="";
                }
                params.put("device",bar_code);
                List<AvdVersion> avdVersions = avd_versionDao.queryAll(true);
                params.put("lastPeriod","");
                if(avdVersions.size()>0) {
                    AvdVersion avdVersion = avdVersions.get(avdVersions.size() - 1);
                    params.put("lastPeriod",avdVersion.getPeriod());
                }
            }
            okTool.doGet(url, new StringCallback() {
                @Override
                public void onBeforeRequest(Request request) {

                }

                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onSuccess(Response response, String t) throws JSONException {
                    JSONObject jsonObject=new JSONObject(t);
                    boolean status = jsonObject.optBoolean("status", false);
                    if(status){
                        Log.i(TAG, "发送心跳数据成功: ");
                    }else {
                        Log.i(TAG, "发送心跳数据失败: ");
                    }

                }

                @Override
                public void onError(Response response, String errorMsg) {

                }
            });

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传数据
     */
    public  void  upPlayRecord(){
        Calendar calendar=Calendar.getInstance();
        long l = System.currentTimeMillis() - 24 * 60 * 60 * 1000;
        calendar.setTimeInMillis(l);
        final String time = DateTimeUtil.getTime(calendar);
        List<PlayRecord> play_list=new ArrayList<>();
        try {
            if(all_or_tody_flag){
                play_list  = playDao.queryno("period", time); //昨天以前数据
            }else {
                play_list  = playDao.query("period", time); //昨天数据
            }
            Log.i(TAG, "昨天视频: "+play_list);
            List<UpPlay>  up_list=new ArrayList<>();
            if(play_list!=null&&play_list.size()>0){
                for (int i = 0; i <play_list.size() ; i++) {
                    PlayRecord playRecord = play_list.get(i);
                    UpPlay up=new UpPlay();
                    up.setId(playRecord.getPlay_id());
                    up.setStart(playRecord.getStart());
                    up.setEnd(playRecord.getEnd());
                    up.setErr(playRecord.getErr());
                    up_list.add(up);
                }
                Gson gson=new Gson();
                final String s = gson.toJson(up_list);
                Log.i(TAG, "上传数据: "+s);
                boolean upTime = DateTimeUtil.getUpTime(11, 13);
                if(upTime&&!upwater_flag) {
                    Random r= new Random();
                    int i = r.nextInt(50)+1;
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            sendPlay(s, time);
                        }
                    },i*60*1000);

                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    /**
     * @param s
     * 发送播放记录数据
     */
    private void sendPlay(final String s, String time) {
        Map<String, String> params = new HashMap<>();
        String url =URLConstant.AD_JSON+URLConstant.GATEWAY_PLAYLOG;
        String bar_code = ShareTool.getInfo(MainActivity.this, "bar_code");
        try {
            if (bar_code.length() < 1) {
                SaveInfo bar = saveDao.queryById("id", "1");
                if(bar!=null) {
                    bar_code = bar.getBarcode();
                }else {
                    bar_code ="";
                }
                params.put("device", bar_code);
                params.put("period", time);
                params.put("logList", s);
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }
        okTool.doPost(url, params, new StringCallback() {
            @Override
            public void onBeforeRequest(Request request) {

            }

            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onSuccess(Response response, String t) throws JSONException {
                JSONObject jsonObject=new JSONObject(t);
                boolean status = jsonObject.optBoolean("status", false);
                if(status){
                    Log.i(TAG, "上传播放数据成功: ");
                    upplay_flag=false; //是否传过 数据
                    all_or_tody_flag=false; //是否上传全部数据
                }else {
                    Log.i(TAG, "上传播放数据失败: ");
                }


            }

            @Override
            public void onError(Response response, String errorMsg) {

            }
        });


    }


    /**
     * @param s_shuizhi
     * @return
     * 水质转换
     */
    private String shuizhiToString(String s_shuizhi) {
        int zhi = Integer.parseInt(s_shuizhi);
        String s_zhi="";
        if(0<=zhi&&zhi<=50){
            s_zhi="优";
        }else if(50<zhi&&zhi<=100){
            s_zhi="良";
        }else if(zhi>100){
            s_zhi="差";
        }
        return s_zhi;
    }

}